var express = require('express');
const sqlQuery = require('../../model/HGmysql');
var router = express.Router();
//获取权限商品列表
router.get('/shoplist', async(req, res) => {
        let pageSize = parseInt(req.query.pageSize)
        currentPage = parseInt(req.query.currentPage)
        let strSql = 'SELECT * FROM classification INNER JOIN shop on codes = category limit ?,?';
        let arr = [(currentPage - 1) * pageSize, pageSize]
        let result = await sqlQuery(strSql, arr);
        //查询数据多少条
        let strSql2 = "select count(id) as name from shop";
        let result1 = await sqlQuery(strSql2);
        let count = result1[0].name;
        return res.json({
            data: {
                result: result,
                count
            }
        })
    })
    //查询
router.get('/selshop', async(req, res) => {
        let pageSize = parseInt(req.query.pageSize)
        currentPage = parseInt(req.query.currentPage)
        let strSql = "SELECT * FROM classification INNER JOIN shop on codes = category WHERE Commodity LIKE '%" + req.query.inputs + "%' limit ?,?;";
        let arr = [(currentPage - 1) * pageSize, pageSize]
        let result = await sqlQuery(strSql, arr);
        let strSq12 = "SELECT count(id) as name FROM shop WHERE Commodity LIKE '%" + req.query.inputs + "%';";
        let result2 = await sqlQuery(strSq12);
        let count = result2[0].name;
        return res.json({
            result,
            count
        })
    })
    //删除'
router.delete('/shoplist/:id', async(req, res, err) => {
        let { id } = req.params;
        let strSql = `delete from shop where id = ${id}`;
        let result = await sqlQuery(strSql);
        if (err) {
            return res.json({
                status: 200,
                data: '删除成功'
            })

        } else {
            return res.json({
                data: '删除失败'
            })
        }
    })
    //批量删除
router.delete('/delshop', async(req, res) => {
        let dels = req.body.id;
        dels.forEach(async(item, i) => {
            let strSql = "delete from shop where id = ?";
            let result = await sqlQuery(strSql, item.id);
        })
        res.json({
            state: 'ok',
            content: '删除成功'
        })
    })
    //分类
router.get('/getclass', async(req, res) => {
    let strSql = `select * from classification`;
    let result = await sqlQuery(strSql);
    let data = result.map(element => {
        return {
            'id': element.codes,
            'cat_name': element.classification,
        }
    });
    res.json({
        status: 200,
        data
    })
})
router.get('/selclass', async(req, res) => {
    let pageSize = parseInt(req.query.pageSize)
    currentPage = parseInt(req.query.currentPage)
    let { id } = req.query
    let strSql = `SELECT * FROM classification INNER JOIN shop on codes = category WHERE classification.codes = ${id} limit ?,?`;
    let arr = [(currentPage - 1) * pageSize, pageSize]
    let data = await sqlQuery(strSql, arr);
    //查询数据多少条
    let strSql2 = `SELECT COUNT(shop.id) FROM classification INNER JOIN shop on codes = category WHERE classification.codes = ${id}`;
    let result1 = await sqlQuery(strSql2);

    let count = result1[0]['COUNT(shop.id)']

    res.json({
        status: 200,
        data,
        count
    })
})
const QRcode = require('qrcode');
router.get('/ewm', (req, res) => {
    QRcode.toDataURL('顺华哈巴狗~', (err, url) => {
        res.send(url)
    })
})
var qr = require('qr-image')
router.get('/create_qrcode', function(req, res, next) {
    var temp_qrcode = qr.image('https://blog.csdn.net/qq_46499070');
    temp_qrcode.pipe(res);
})
router.get('/getTo', async(req, res) => {

    let pageSize = parseInt(req.query.pageSize)
    currentPage = parseInt(req.query.currentPage)
    let strSql = 'SELECT * FROM classification INNER JOIN treviewed on codes = category limit ?,?';
    let arr = [(currentPage - 1) * pageSize, pageSize]
    let result = await sqlQuery(strSql, arr);
    //查询数据多少条
    let strSql2 = "select count(id) as name from treviewed";
    let result1 = await sqlQuery(strSql2);
    let count = result1[0].name;
    return res.json({
        data: {
            result,
            count
        }
    })
})
router.put('/editshenhe/:id', async(req, res) => {
    console.log(req.body.data);
    let { resource, desc } = req.body.data
    let strSql = `update treviewed set stare=?,descs=? WHERE id=${req.params.id}`;
    let arr = [resource, desc]
    let result = await sqlQuery(strSql, arr);
    return res.json({
        status: 200,
        result,
        data: '修改成功'
    })
})
router.post('/addshenhe', async(req, res) => {
        let strSql2 = `SELECT * FROM treviewed WHERE id = ${req.body.data.data}`;
        let result1 = await sqlQuery(strSql2);
        let { nameeds, describes, datetime, Commodity, address, Storeid, category, picture, Price, stare, Repository, username, descs } = result1[0]
        let shll = req.body.data.shll
        if (stare !== '已通过') {
            let strSql = "insert into audit (namesd,describes,datetime,Commodity,address,Storeid,category,picture,Price,stare,Repository,username,descs,shlls) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
            let arr = [nameeds, describes, datetime, Commodity, address, Storeid, category, picture, Price, stare, Repository, username, descs, shll]
            let result = await sqlQuery(strSql, arr);
            return res.json('ok')
        } else {
            let strSql = "insert into audit (namesd,describes,datetime,Commodity,address,Storeid,category,picture,Price,stare,Repository,username,descs,shlls) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
            let arr = [nameeds, describes, datetime, Commodity, address, Storeid, category, picture, Price, stare, Repository, username, descs, shll]
            let result = await sqlQuery(strSql, arr);
            //添加到shop
            let kk = req.body.data.shll
            console.log(kk);
            let strSql2 = `insert into shop (namesd,describes,datetimesd,Commodity,address,Storeid,category,picture,Price,Repository,username,sh) values(?,?,?,?,?,?,?,?,?,?,?,'${kk}')`
            let arr1 = [nameeds, describes, datetime, Commodity, address, Storeid, category, picture, Price, Repository, username, descs]
            let result2 = await sqlQuery(strSql2, arr1);
            return res.json('ok')
        }
    })
    //删除'
router.delete('/editshenhe/:id', async(req, res, err) => {
    let { id } = req.params;
    let strSql = `delete from treviewed where id = ${id}`;
    let result = await sqlQuery(strSql);
    if (err) {
        return res.json({
            status: 200,
            data: '删除成功'
        })

    } else {
        return res.json({
            data: '删除失败'
        })
    }
})
router.get('/getMt', async(req, res) => {
        let pageSize = parseInt(req.query.pageSize)
        currentPage = parseInt(req.query.currentPage)
        let user = req.query.user
        let strSql = `SELECT * FROM classification INNER JOIN audit on codes = category WHERE audit.shlls = '${user}' limit ?,?`;
        let arr = [(currentPage - 1) * pageSize, pageSize]
        let result = await sqlQuery(strSql, arr);
        //查询数据多少条
        let strSql2 = "select count(id) as name from audit";
        let result1 = await sqlQuery(strSql2);
        let count = result1[0].name;
        return res.json({
            data: {
                result,
                count
            }
        })
    })
    //添加商品等待审核
router.post('/addshop', (req, res) => {
        //时间
        var d = new Date();
        var year = d.getFullYear();
        var month = change(d.getMonth() + 1);
        var day = change(d.getDate());
        var hour = change(d.getHours());
        var minute = change(d.getMinutes());
        var second = change(d.getSeconds());

        function change(t) {
            if (t < 10) {
                return "0" + t;
            } else {
                return t;
            }
        }
        var Num = "";
        for (var i = 0; i < 5; i++) {
            Num += Date.now() + Math.floor(Math.random() * 10);
        }
        let cckk = '144782' + Num.slice(54)
        var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
        let { name, Commodity, address, Repository, Price, desc, classed, user } = req.body
        let imgdata = req.files.file
        let path = `public/shopload/uploadshop_` + req.files.file.md5 + Date.now() + '.jpg'
        let paths = `http://localhost:3000${path.slice(6)}`

        imgdata.mv(path, async function(err) {
            if (err) {
                return res.status(500).send(err);
            } else {
                let strSql = "insert into treviewed (nameeds,describes,datetime,Commodity,address,Storeid,category,picture,Price,Repository,username) values(?,?,?,?,?,?,?,?,?,?,?)"
                let arr = [name, desc, time, Commodity, address, cckk, classed, paths, Price, Repository, user]
                let result = await sqlQuery(strSql, arr);
                return res.json('ok')
            }
        })
    })
    //成功商品
router.get('/cgshop', async(req, res) => {
    let username = req.query.name;
    let strSql = `SELECT * FROM classification INNER JOIN shop on codes = category WHERE shop.username = '${username}'`
    let quantitys = `SELECT COUNT(stare) FROM  treviewed WHERE username = '${username}'`;
    let quantitn = await sqlQuery(quantitys);
    let quantity = quantitn[0]['COUNT(stare)']
    let quanw = `SELECT COUNT(stare) FROM  audit WHERE username = '${username}' AND audit.stare = '未通过'`
    let quans = await sqlQuery(quanw);
    let quanh = quans[0]['COUNT(stare)']
    let result = await sqlQuery(strSql);
    res.json({
        status: 'ok',
        result,
        quantity,
        quanh
    })
})
router.get('/shshop', async(req, res) => {
    let username = req.query.name;
    let strSql = `SELECT * FROM classification INNER JOIN treviewed on codes = category WHERE treviewed.username = '${username}'`
    let result = await sqlQuery(strSql);
    res.json({
        status: 'ok',
        result
    })
})
router.get('/wtshop', async(req, res) => {
    let username = req.query.name;
    let strSql = `SELECT * FROM classification INNER JOIN audit on codes = category WHERE audit.username = '${username}' AND audit.stare = '未通过'`
    let result = await sqlQuery(strSql);
    res.json({
        status: 'ok',
        result
    })
})
module.exports = router;